package com.sduept.nwld.primaryequipment.rest;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sduept.bigdata.fault.special.maintenance.manager.MaintenanceManager;
import com.sduept.bigdata.fault.special.maintenance.manager.MaintenanceQueryManager;
import com.sduept.bigdata.special.maintenance.model.MaintenanceStation;
import com.sduept.bigdata.special.maintenance.model.MaintenanceStationBreaker;
import com.sduept.cim.model.core.Substation;
import com.sduept.nwld.dataserver.manager.cim.CimManager;
import com.sduept.utils.DateUtil;
@RestController
@RequestMapping("/specialMaintenace/")
public class SpecialMaintenaceServices {
	@Autowired
	private MaintenanceManager sm;

	@Autowired
	private CimManager cm;
	
	@Autowired
	private MaintenanceQueryManager manager;

	/*
	 * Date类型时间获取年份
	 *
	 * @param time
	 *
	 * @return dateTime
	 */
	private int getYear(Date time) {
		Calendar lt = Calendar.getInstance();
		lt.setTime(time);
		int year = lt.get(Calendar.YEAR);// 当前年份
		return year;
	}

	/**
	 * 获取全网的某种类型的未完成的string列表
	 * @param mb
	 * @param station
	 * @return
	 */
	private String[] getTbData(MaintenanceStationBreaker mb, MaintenanceStation station) {
		String breakerName = mb.getName();
		Date tripA = mb.getLastTripATime();
		Date tripB = mb.getLastTripBTime();
		Date tripC = mb.getLastTripCTime();
		String bayName = mb.getBayName();
		String a = tripA == null ? "" : DateUtil.getStringDate(tripA, DateUtil.pattern_ymd);
		String b = tripB == null ? "" : DateUtil.getStringDate(tripB, DateUtil.pattern_ymd);
		String c = tripC == null ? "" : DateUtil.getStringDate(tripC, DateUtil.pattern_ymd);
		String stationName = station.getStation();
		String planTime = "";
		if (null != station.getChuandongTime()) {
			planTime = DateUtil.getStringDate(station.getChuandongTime(), DateUtil.pattern_ymd);
		}
		String isFinishedBefore = "是" ;
		Date finishedTime = station.getFinishedTime();
		String finishedTimeStr = finishedTime == null ? "" : DateUtil.getStringDate(finishedTime, DateUtil.pattern_ymd);
		String[] s = { stationName, bayName, breakerName, a, b, c, planTime, isFinishedBefore,finishedTimeStr };
		return s;
	}
	
	/**
	 * 将数据整理成table显示的模样--MaintenanceStation类型
	 * @param station
	 * @return
	 */
	private String[] getTbData(MaintenanceStation station) {
		String bayName = station.getStation();
		String a = station.getPhaseALastFault();
		String b = station.getPhaseBLastFault();
		String c = station.getPhaseCLastFault();
		String stationName = station.getStation();
		String operationDepartment = station.getOperationDepartment();
		String planTime = "";
		if (null != station.getChuandongTime()) {
			planTime = DateUtil.getStringDate(station.getChuandongTime(), DateUtil.pattern_ymd);
		}
		Date finishedTime = station.getFinishedTime();
		String finishedTimeStr = finishedTime == null ? "" : DateUtil.getStringDate(finishedTime, DateUtil.pattern_ymd);
		String[] s = { stationName, bayName,operationDepartment, a, b, c, planTime,finishedTimeStr };
		return s;
	}
	

	/**
	 * 根据stationId和time获取未完成传动的断路器信息。点击地图上的站点时调用
	 *
	 * @param name
	 * @return
	 */

	@GetMapping("/getUnfinishedBreakerBySid/{sid}/{time}")
	public String getUnfinishedBreakerBySid(@PathVariable("sid") String sid,@PathVariable("time") String time) {
		Date currentTime = DateUtil.getDateByString(time, "yyyy-MM-dd HH:mm:ss");
		int currentYear = getYear(currentTime);// 当前年份
		JSONObject jso = new JSONObject();
		List<String[]> finishedList = new ArrayList<String[]>();
		List<String[]> demandList = new ArrayList<String[]>();
		List<String[]> planList = new ArrayList<String[]>();
		List<MaintenanceStation> spBays = sm.getMaintenanceStationsByStationIdAndYear(sid, currentYear);
		int finishedNum = 0;// 计算特维间隔数目
		for (MaintenanceStation m : spBays) {
			if (m.isFinish()) {
				finishedNum++;
				List<MaintenanceStationBreaker> finishedBreakerList = sm.getBreakersBybayIdAndYear(m.getId(),
						currentYear);
				for (MaintenanceStationBreaker b : finishedBreakerList) {
					finishedList.add(getTbData(b, m));
				}
			} else {
				// 判断是否应该在6月30号之前完成
				//if (m.isFinishBefore()) {//应该在6月30号之前完成，但未完成的，放进demandList
					List<MaintenanceStationBreaker> demandBreakerList = sm.getBreakersBybayIdAndYear(
							m.getId(), currentYear);
					for (MaintenanceStationBreaker b : demandBreakerList) {
						demandList.add(getTbData(b, m));
					}
				/*} else {//未要求6月30号之前完成的，并且还未完成的，放进planList
					List<MaintenanceStationBreaker> planBreakerList = sm.getBreakersBybayIdAndYear(m.getId(),
							currentYear);
					for (MaintenanceStationBreaker b : planBreakerList) {
						planList.add(getTbData(b, m));
					}
				}*/
			}
		}
		// 得到完成传动的断路器信息
		jso.put("total", spBays.size());// 总间隔数
		jso.put("finishedNum", finishedNum);
		jso.put("unfinishedNum", spBays.size() - finishedNum);
		jso.put("demand", demandList);// 未按要求时间完成
		jso.put("plan", planList);// 未按计划完成
		jso.put("finished", finishedList);// 已完成的
		return jso.toJSONString();
	}

	/**
	 * 根据time获取全网所有的特维站
	 *
	 * @param time
	 * @return [stationName]
	 */

	@GetMapping("/getAllSpecialMaintanceStation/{time}")
	public String getAllSpecialMaintanceStation(@PathVariable("time") String time) {
		Date currentTime = DateUtil.getDateByString(time, DateUtil.pattern_ymdhms);
		int currentYear = getYear(currentTime);// 当前年份
		Map<String, String> stationMap = sm.getStationMap(currentYear);
		JSONObject itemJSONObj = JSONObject.parseObject(JSON.toJSONString(stationMap));
		return itemJSONObj.toString();
	}

	/**
	 * 根据time获取全网未完成传动的信息
	 *
	 * @param time
	 * @return [stationName,beakerName,A,B,C,planTime,是/否]
	 */

	@GetMapping("/getAllUnfinishedBreaker/{time}")
	public String getAllUnfinishedBreaker(@PathVariable("time") String time) {
		Date currentTime = DateUtil.getDateByString(time, "yyyy-MM-dd HH:mm:ss");
		int currentYear = getYear(currentTime);// 当前年份
		JSONObject jso = new JSONObject();
		Set<String> allSpStations = new HashSet<String>();// 存放所有的特维站
		List<MaintenanceStation> spBays = sm.getMaintenanceStationsByYear(currentYear);// 所有的特维设备
		for (MaintenanceStation s : spBays) {
			allSpStations.add(s.getSubStationId());
		}
		List<MaintenanceStationBreaker> beakerList = sm.getBreakersByYear(currentYear);
		jso.put("totalBreaker", beakerList.size());
		Set<String> unfinishedStationId = new HashSet<String>();// 存放未已完成站点id
		List<String[]> finishedList = new ArrayList<String[]>();
		List<String[]> demandList = new ArrayList<String[]>();
		List<String[]> planList = new ArrayList<String[]>();
		for (MaintenanceStationBreaker breaker : beakerList) {
			if (null != breaker) {
				MaintenanceStation stationById = null;
				for (MaintenanceStation s : spBays) {
					if (breaker.getPid().equals(s.getId())) {
						stationById = s;
						break;
					}
				}
				// MaintenanceStation stationById =
				// sm.getMaintenanceStationById(breaker.getPid());
				if (!sm.isFinishedByDemand(breaker, currentTime, stationById)) {
					demandList.add(getTbData(breaker, stationById));
					unfinishedStationId.add(breaker.getStationId());
				} else if (!sm.isFinishedByCurrent(breaker, currentTime, stationById)) {
					planList.add(getTbData(breaker, stationById));
					unfinishedStationId.add(breaker.getStationId());
				} else {
					finishedList.add(getTbData(breaker, stationById));
				}
			}
		}
		jso.put("breakerFinished", finishedList.size());
		jso.put("breakerUnfinished", beakerList.size() - finishedList.size());
		jso.put("totalStation", allSpStations.size());
		jso.put("stationUnfinished", unfinishedStationId.size());
		jso.put("stationFinished", allSpStations.size() - unfinishedStationId.size());
		jso.put("demand", demandList);// 未按要求时间完成
		jso.put("plan", planList);// 未按计划完成
		jso.put("finished", finishedList);// 已完成的
		return jso.toJSONString();
	}
	
	/**
	 * 根据stationId和year获取该站点下所有的跳闸记录
	 *
	 * @param name
	 * @return
	 */

	@GetMapping("/getBreakerActBySid/{sid}/{year}")
	public String getBreakerActBySid(@PathVariable("sid") String sid,@PathVariable("year") int year) {
		List<MaintenanceStation> spBays = sm.getMaintenanceStationsByStationIdAndYear(sid, year);
		List<MaintenanceStationBreaker> beakerList = sm.getBreakersByStationIdAndYear(sid, year);
		List<String[]> rtn = new ArrayList<String[]>();
		for (MaintenanceStationBreaker breaker : beakerList) {
			if (null != breaker) {
				MaintenanceStation stationById = null;
				for (MaintenanceStation s : spBays) {
					if (breaker.getPid().equals(s.getId())) {
						stationById = s;
						break;
					}
				}
				rtn.add(getTbData(breaker, stationById));

			}
		}
		return net.sf.json.JSONArray.fromObject(rtn).toString();
	}

	private static String getColorY2R(int v) {
		int ic = 255 * v / 100;
		String c = String.format("%02x", 255 - ic);
		return "#ff" + c + "00";

	}
	
	/**
	 * 根据stationId和time获取未完成传动的断路器信息。点击地图上的站点时调用
	 *
	 * @param name
	 * @return
	 */

	@GetMapping("/getUnfinishedSpecialStationBySid/{sid}")
	public String getUnfinishedSpecialStationBySid(@PathVariable("sid") String sid) {
		JSONObject jso = new JSONObject();
		List<String[]> finishedList = new ArrayList<String[]>();
		List<String[]> demandList = new ArrayList<String[]>();
		List<String[]> planList = new ArrayList<String[]>();
		List<MaintenanceStation> specialStations = manager.getMaintenanceStationByStationId(sid);
		int finishedNum = 0;// 计算特维间隔数目
		for(MaintenanceStation specialStation:specialStations) {
			if(specialStation.isFinish()) {
				finishedNum ++;
				finishedList.add(getTbData(specialStation));
			}else {
				demandList.add(getTbData(specialStation));
			}
		}
		// 得到完成传动的断路器信息
		jso.put("total", specialStations.size());// 总间隔数
		jso.put("finishedNum", finishedNum);
		jso.put("unfinishedNum", specialStations.size() - finishedNum);
		jso.put("demand", demandList);// 未按要求时间完成
		jso.put("plan", planList);// 未按计划完成
		jso.put("finished", finishedList);// 已完成的
		return jso.toJSONString();
	}
	
	/**
	 * 根据年份判断特维站的完成情况（未完成/总数）,地图用 220kV / 500kV
	 * @param time
	 * @return
	 */

	@GetMapping("/getSpecialStationsForMap/{voltageParam}")
	public String getSpecialStationsForMap(@PathVariable("voltageParam") String voltageParam) {
		if(StringUtils.isEmpty(voltageParam)) {
			voltageParam = "500";
		}
		int voltage=Integer.parseInt(voltageParam);
		List<MaintenanceStation> spStations = manager.getMaintenanceStationsByVoltage(voltage);// 所有特维间隔
		int finishedBreakerNum = 0;// 已完成间隔总数
		int unfinishedStationNum = 0;// 未完成站点总数
		JSONObject jo = new JSONObject();
		JSONArray specialStation = new JSONArray();
		Map<String, int[]> spStationIds = new HashMap<>();// <特维站id,[总间隔数，完成数]>
		for (MaintenanceStation s : spStations) {
			String sId = s.getSubStationId();
			if(StringUtils.isBlank(sId)) {
				continue;
			}
			int[] nums = spStationIds.get(sId);
			// 总数
			if (null == nums) {
				nums = new int[] { 1, 0 };
			} else {
				nums[0]++;
			}
			// 已完成
			if (s.isFinish()) {
				nums[1]++;
				finishedBreakerNum++;// 已完成的间隔总数
			}
			spStationIds.put(sId, nums);
		}
		for (Entry<String, int[]> entry : spStationIds.entrySet()) {
			String sId = entry.getKey();
			if(StringUtils.isBlank(sId)) {
				continue;
			}
			int[] nums = entry.getValue();
			Substation stat = cm.getStationById(sId);
			JSONObject jso = new JSONObject();
			jso.put("station", stat);
			int breakerNum = nums[0];
			int unfinishedNum = nums[0] - nums[1];
			if (unfinishedNum > 0 || breakerNum == 0) {
				// 如果没有找到该站下面的特维断路器，就当做未完成
				unfinishedStationNum++;
			}
			int level = 100;
			if (breakerNum != 0) {
				level = unfinishedNum / breakerNum * 100;
			}
			jso.put("level", level);
			jso.put("style", getColorY2R(level));
			specialStation.add(jso);
		}
		jo.put("totalStation", spStationIds.size());
		jo.put("totalBreaker", spStations.size());
		jo.put("breakerFinished", finishedBreakerNum);
		jo.put("breakerUnfinished", spStations.size() - finishedBreakerNum);
		jo.put("stationUnfinished", unfinishedStationNum);
		jo.put("stationFinished", spStationIds.size() - unfinishedStationNum);
		jo.put("value", specialStation);
		return jo.toJSONString();
	}
	
}
